package com.example.administrator.School.until;

import android.os.Bundle;

import com.example.administrator.School.common.result.Result;
import com.example.administrator.School.widget.GsonUtils;
import com.example.administrator.School.widget.SimplexToast;
import com.loopj.android.http.TextHttpResponseHandler;

import java.lang.reflect.Type;

import cz.msebera.android.httpclient.Header;

/**
 * Created by ChrisWong on 2017/1/17.
 */
public abstract class BaseDetailActivity<T> extends BaseActivity {

    protected TextHttpResponseHandler mHandler;
    protected Result<T> result;

    @Override
    protected boolean initBundle(Bundle bundle){
        return super.initBundle(bundle);
    }

    @Override
    protected void initWidget(){
        super.initWidget();
    }
    //返回键
//    protected int getLeftIconRes() {
//        return R.drawable.selector_nav_back_light;
//    }
//    @Override
//    protected View.OnClickListener getLeftIconClickListener() {
//        return new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        };
//    }
    @Override
    protected void initData() {
        super.initData();
        // 加载监听器
        mHandler = new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    result = GsonUtils.fromJson(responseString, getType());
                    if (result.getData()!=null||Result.RESULT_SUCCESS.equals(result.getCode()) || result.getUser()!=null) {
                        setData(result);
                        onRequestSuccess(1);
                    } else {
                        SimplexToast.show(getApplicationContext(),result.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(statusCode, headers, responseString, e);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                onRequestFinish();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                onRequestError();
            }
        };
    }

    protected abstract Type getType();

    /**
     * 从服务器获取数据后，调用此方法
     * @param result
     */
    protected abstract void setData(Result<T> result);


    protected void onRequestSuccess(int code) {
    }

    protected void onRequestFinish() {
    }

    protected void onRequestError() {
        SimplexToast.show(getApplicationContext(), "读取数据失败！");
    }

}
